import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { setArticleContent } from '@/store/modules/articleSlice'
import { useDispatch } from 'react-redux'

function MyEditor({artilceContent=""}) {
  const dispatch = useDispatch()
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null) // TS 语法

  // 编辑器内容
  const [html, setHtml] = useState('')

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {} // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: '请输入内容...',
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])


  // 获取编辑器的内容
  const getEditorContent = (editor:IDomEditor)=>{
    console.log(editor.getHtml())
    // 存储当前的编辑器内容
    setHtml(editor.getHtml())
    // 存储文章内容到RTK中
    dispatch(setArticleContent(editor.getHtml()))
  }

  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={artilceContent}
          onCreated={setEditor}
          onChange={getEditorContent}
          mode="default"
          style={{ height: '300px', overflowY: 'hidden' }}
        />
      </div>
    </>
  )
}

export default MyEditor